
package com.ztao.service.impl;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.apArticle.dto.ArticleDto;
import com.heima.model.common.apArticle.dto.ArticleHomeDto;
import com.heima.model.common.apArticle.dto.ArticleInfoDto;
import com.heima.model.common.apArticle.vos.HotArticleVo;
import com.heima.model.common.behavior.LikesBehaviorDto;
import com.heima.model.common.apArticle.pojos.ApArticle;
import com.heima.model.common.apArticle.pojos.ApArticleConfig;
import com.heima.model.common.apArticle.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mess.ArticleVisitStreamMess;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.ztao.common.constants.ArticleConstants;
import com.ztao.common.constants.BehaviorConstants;
import com.ztao.mapper.ApArticleConfigMapper;
import com.ztao.mapper.ApArticleContentMapper;
import com.ztao.mapper.ArticleMapper;
import com.ztao.redis.CacheService;
import com.ztao.service.ApArticleContentService;
import com.ztao.service.ArticleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
    public class ArticleServiceImpl  extends ServiceImpl<ArticleMapper, ApArticle> implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private ApArticleContentMapper apArticleContentMapper;
    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;
    @Resource
    private ApArticleContentService apArticleContentService;

    //设置size常量   当页面传递过来的>50的时候，默认设置的最大数是50
    private final static short MAX_PAGE_SIZE=50;



    @Override
    public ResponseResult<ApArticle> load(ArticleHomeDto dto, Integer type) {
        //1.校验参数 -size
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 100;
        }
        //如果size<50 size=size  如果size>50  size=50
        size = Math.min(size, MAX_PAGE_SIZE);
        //把size赋值给dto
        dto.setSize(size);

        //2.校验参数 -频道
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag("__all__");
        }

        //3.校验参数 -时间
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }

        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }

        //2.查询数据
        List<ApArticle> apArticleList= articleMapper.loadArticleList(dto,type);

        //3.封装结果
        return ResponseResult.okResult(apArticleList);
    }

    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.封装参数
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //3.进行保存  判断是新增还是修改  id
        if (dto.getId() == null) {  //新增
            //保存文章基本信息
            articleMapper.insert(apArticle);
            //保存内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(apArticle.getId());
            content.setContent(dto.getContent());
            apArticleContentMapper.insert(content);

            //保存配置表  -自己实现
            ApArticleConfig apArticleConfig=new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId());
            apArticleConfig.setIsComment(true);
            apArticleConfig.setIsDelete(false);
            apArticleConfig.setIsDown(false);
            apArticleConfig.setIsForward(true);
            apArticleConfigMapper.insert(apArticleConfig);


        } else {
            //修改文章
            articleMapper.updateById(apArticle);

            //修改内容
            QueryWrapper<ApArticleContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ApArticleContent::getArticleId, dto.getId());
            ApArticleContent content = apArticleContentMapper.selectOne(queryWrapper);
            content.setContent(dto.getContent());
            apArticleContentMapper.updateById(content);

            //修改配置表

        }
        apArticleContentService.createStaticUrl(apArticle.getId());

        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 加载文章详情，数据回显
     * @param dto
     * @return
     */
    @Resource
    private CacheService cacheService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //0.检查参数
        if(dto == null || dto.getAuthorId() == null || dto.getAuthorId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false,islike=false,isunlike=false,iscollection=false;

        ApUser user = AppThreadLocalUtil.getUser();
        if(user != null){
            //喜欢行为
            String o = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(o)){
                islike = true;
            }
            //不喜欢行为
            String unlike = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(unlike)){
                isunlike=true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR+user.getId(),dto.getArticleId().toString());
            if(StringUtils.isNotBlank(collctionJson)){
                iscollection = true;
            }
            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            System.out.println(score);
            if(score != null){
                isfollow = true;
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("isfollow",isfollow);
        map.put("islike",islike);
        map.put("isunlike",isunlike);
        map.put("iscollection",iscollection);

        return ResponseResult.okResult(map);
    }

    /**
     * 加载文章列表
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true  是首页  flase 非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto dto, Short type, boolean firstPage) {
        if(firstPage){
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if(StringUtils.isNotBlank(jsonStr)){
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(dto, Integer.valueOf(type));
    }



    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        //1.更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(mess);
        //2.计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);

    }

    /**
     * 替换数据并且存入到redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceDataToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            //如果缓存中存在该文章，只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            //如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hot = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hot);
                        hot.setScore(score);
                        hotArticleVoList.add(hot);
                    }


                } else {
                    HotArticleVo hot = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hot);
                    hot.setScore(score);
                    hotArticleVoList.add(hot);
                }
            }
            //缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));

        }
    }

    /**
     * 更新文章行为数量
     * @param mess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess mess) {
//        System.out.println("mess-------------- = " + mess);
//        System.out.println("messId-------------- = " + mess.getArticleId());
        ApArticle apArticle = getById(mess.getArticleId());
//        System.out.println("11111111111111111"+apArticle);


        apArticle.setCollection(apArticle.getCollection()==null?0:apArticle.getCollection()+mess.getCollect());
        System.out.println("apArticle---getCollection = " + apArticle.getCollection());
        apArticle.setComment(apArticle.getComment()==null?0:apArticle.getComment()+mess.getComment());
        apArticle.setLikes(apArticle.getLikes()==null?0:apArticle.getLikes()+mess.getLike());
        apArticle.setViews(apArticle.getViews()==null?0:apArticle.getViews()+mess.getView());
        updateById(apArticle);
        return apArticle;

    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }







}
